package com.xd.core.system.service.impl;

import cn.hutool.json.XML;
import com.alibaba.fastjson.JSONObject;
import com.xd.common.exception.XkdException;
import com.xd.common.properties.SZLZSmsProperties;
import com.xd.common.properties.SendALProperties;
import com.xd.common.properties.SendSubMailProperties;
import com.xd.common.properties.SendTXProperties;
import com.xd.common.util.MD5Util;
import com.xd.common.util.RequestEncoder;
import com.xd.common.util.RestTemplateUtil;
import com.xd.common.util.SendMessageUtil;
import com.xd.core.system.service.MsmService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

@Service
@Slf4j
public class MsmServiceImpl implements MsmService {
    private static final String TYPE_MD5 = "md5";
    private static final String TYPE_SHA1 = "sha1";
    /*
     * 阿里云
     * */
    @Resource
    private SendALProperties sendALProperties;
    /*
     * 腾讯云
     * */
    @Resource
    private SendTXProperties sendTXProperties;

    @Resource
    private SZLZSmsProperties szlzSmsProperties;

    /*
     * submail短信
     * */
    @Resource
    private SendSubMailProperties sendSubMailProperties;
    @Autowired
    private RestTemplateUtil restTemplateUtil;

    //发送短信的方法
    @Override
    public String send(Map<String, Object> param, String phone) {
        if (StringUtils.isEmpty(phone))
            throw new XkdException("电话号码不能为空");

        String[] phones = {phone};
        String[] paramTX = {param.get("code").toString()};

        //阿里云不行就发下一个腾讯云
        //成功是OK
        String b = SendMessageUtil.sendALMsg(sendALProperties.getSignatureName(), sendALProperties.getAccessKeyId(), sendALProperties.getSecret(), sendALProperties.getModelCode(), phone, param);
        if (b.equalsIgnoreCase("OK")) {
            log.info("阿里云发送成功");
            return b;
        }
        String a = SendMessageUtil.sendTXMsg(sendTXProperties.getSmsSdkAppId(), sendTXProperties.getSignName(), sendTXProperties.getSecretKey(), sendTXProperties.getSecretId(), sendTXProperties.getTemplateId(), phones, paramTX);
        assert a != null;
        if (a.equalsIgnoreCase("OK")) {
            log.info("腾讯云发送成功");
            return a;
        }

        return "fail";
    }


    public com.aliyun.teaopenapi.Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                // 必填，您的 AccessKey ID
                .setAccessKeyId(accessKeyId)
                // 必填，您的 AccessKey Secret
                .setAccessKeySecret(accessKeySecret);
        // Endpoint 请参考 https://api.aliyun.com/product/Dm
        config.endpoint = "dm.aliyuncs.com";
        return new com.aliyun.teaopenapi.Client(config);
    }

    /**
     * API 相关
     *
     * @return OpenApi.Params
     */
    public com.aliyun.teaopenapi.models.Params createApiInfo() throws Exception {
        com.aliyun.teaopenapi.models.Params params = new com.aliyun.teaopenapi.models.Params()
                // 接口名称
                .setAction("SingleSendMail")
                // 接口版本
                .setVersion("2015-11-23")
                // 接口协议
                .setProtocol("HTTPS")
                // 接口 HTTP 方法
                .setMethod("POST")
                .setAuthType("AK")
                .setStyle("RPC")
                // 接口 PATH
                .setPathname("/")
                // 接口请求体内容格式
                .setReqBodyType("json")
                // 接口响应体内容格式
                .setBodyType("json");
        return params;
    }

    private String getTimestamp() {
        CloseableHttpClient closeableHttpClient = HttpClientBuilder.create().build();
        HttpGet httpget = new HttpGet(sendSubMailProperties.getTimestampurl());
        try {
            HttpResponse response = closeableHttpClient.execute(httpget);
            HttpEntity httpEntity = response.getEntity();
            String jsonStr = EntityUtils.toString(httpEntity, "UTF-8");
            if (jsonStr != null) {
                JSONObject json = JSONObject.parseObject(jsonStr);
                return json.getString("timestamp");
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /*
     * submail短信
     * */
    @Override
    public String sendSmsDJKJ(String to, String content) {
        TreeMap<String, String> requestData = new TreeMap<String, String>();
        String appid = sendSubMailProperties.getAppid();
        String appkey = sendSubMailProperties.getAppkey();
        String sign_type = "md5";
        String sign_version = "2";
        //组合请求数据
        requestData.put("appid", appid);
        requestData.put("to", to);
        if (sign_type.equals(TYPE_MD5) || sign_type.equals(TYPE_SHA1)) {
            String timestamp = getTimestamp();
            requestData.put("timestamp", timestamp);
            requestData.put("sign_type", sign_type);
            requestData.put("sign_version", sign_version);
            String signStr = appid + appkey + RequestEncoder.formatRequest(requestData) + appid + appkey;
            requestData.put("signature", RequestEncoder.encode(sign_type, signStr));
        } else {
            requestData.put("signature", appkey);
        }
        requestData.put("content", content);
        //post请求
        HttpPost httpPost = new HttpPost(sendSubMailProperties.getUrl());
        httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("Content-Type", "application/json");
        StringEntity entity = new StringEntity(JSONObject.toJSONString(requestData), "UTF-8");
        httpPost.setEntity(entity);
        try {
            CloseableHttpClient closeableHttpClient = HttpClientBuilder.create().build();
            HttpResponse response = closeableHttpClient.execute(httpPost);
            HttpEntity httpEntity = response.getEntity();
            if (httpEntity != null) {
                String jsonStr = EntityUtils.toString(httpEntity, "UTF-8");
                return JSONObject.parseObject(jsonStr).getString("status");
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    @Override
    public String SZLZSendSms(String phone, String content) {
        Map<String, String> errorCodeMap = new HashMap<>();
        errorCodeMap.put("0", "成功");
        errorCodeMap.put("1", "登录密码错误");
        errorCodeMap.put("2", "企业ID或登录名错误");
        errorCodeMap.put("3", "余额不足");
        errorCodeMap.put("4", "用户归属服务器错误");
        errorCodeMap.put("5", "帐户停用或不存在");
        errorCodeMap.put("6", "内容为空");
        errorCodeMap.put("7", "号码为空");
        errorCodeMap.put("8", "号码超过最大限制数");
        errorCodeMap.put("9", "内容包含关键字");
        errorCodeMap.put("10", "时间格式错误");
        errorCodeMap.put("11", "非法操作导致ip被锁");
        errorCodeMap.put("12", "访问过快");
        errorCodeMap.put("13", "批量一对一参数格式错误");
        errorCodeMap.put("14", "批量一对一出现重复信息(号码，内容同时重复)");
        errorCodeMap.put("15", "签名未报备");
        errorCodeMap.put("16", "单位时间内该号码超过最大发送限制");
        errorCodeMap.put("17", "签名必须在【4，10】字符间");
        errorCodeMap.put("18", "内容涉嫌营销内容");
        errorCodeMap.put("27", "30秒内出现重复发送");
        errorCodeMap.put("28", "内容超过4000字符");
        errorCodeMap.put("99", "系统内部错误");
        HashMap<String, Object> map = new HashMap<>();
        map.put("enterpriseID", szlzSmsProperties.getEnterpriseId());
        map.put("loginName", szlzSmsProperties.getLoginName());
        String s = MD5Util.MD5a32(szlzSmsProperties.getPassword());
        map.put("password", s);
        map.put("content", content);
        map.put("mobiles", phone);
        ResponseEntity<String> stringResponseEntity = restTemplateUtil.postForm(szlzSmsProperties.getUrl(), map, String.class);
        String body = stringResponseEntity.getBody();
        cn.hutool.json.JSONObject jsonObject = XML.toJSONObject(body);
        cn.hutool.json.JSONObject Response = jsonObject.getJSONObject("Response");
        String result = Response.getStr("Result");
        if (result.equals("0")) {
            log.info("短信发送成功");
            return "success";
        } else {
            String errorMessage = errorCodeMap.getOrDefault(result, "未知错误");
            log.info("短信发送失败，错误码：" + result + ", 错误信息：" + errorMessage);
            return "fail: " + errorMessage;
        }

    }
    @Override
    public String sendSmsDJKJBaokun(String to, String content) {
        if (StringUtils.isBlank(to)) return null;
        TreeMap<String, String> requestData = new TreeMap<String, String>();
        String appid = sendSubMailProperties.getAppidBaokun();
        String appkey = sendSubMailProperties.getAppkeyBaokun();
        String sign_type = "md5";
        String sign_version = "2";
        //组合请求数据
        requestData.put("appid", appid);
        requestData.put("to", to);
        if (sign_type.equals(TYPE_MD5) || sign_type.equals(TYPE_SHA1)) {
            String timestamp = getTimestamp();
            requestData.put("timestamp", timestamp);
            requestData.put("sign_type", sign_type);
            requestData.put("sign_version", sign_version);
            String signStr = appid + appkey + RequestEncoder.formatRequest(requestData) + appid + appkey;
            requestData.put("signature", RequestEncoder.encode(sign_type, signStr));
        } else {
            requestData.put("signature", appkey);
        }
        requestData.put("content", content);
        //post请求
        HttpPost httpPost = new HttpPost(sendSubMailProperties.getUrl());
        httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("Content-Type", "application/json");
        StringEntity entity = new StringEntity(JSONObject.toJSONString(requestData), "UTF-8");
        httpPost.setEntity(entity);
        try {
            CloseableHttpClient closeableHttpClient = HttpClientBuilder.create().build();
            HttpResponse response = closeableHttpClient.execute(httpPost);
            HttpEntity httpEntity = response.getEntity();
            if (httpEntity != null) {
                String jsonStr = EntityUtils.toString(httpEntity, "UTF-8");
                return JSONObject.parseObject(jsonStr).getString("status");
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    @Override
    public String sendH5(String to, String content1, String content2) {
        String s1 = sendSmsDJKJBaokun(to, content1);
        if (s1.equalsIgnoreCase("success")) {
            log.info("发送submail");
            return s1;
        }
        String s2 = SZLZSendSms(to, content2);
        if (s2.equalsIgnoreCase("success")) {
            log.info("发送量子短信");
            return s2;
        }
        return "fail";
    }
}
